package com.ews.onlineexchange.endpoint;

import java.io.IOException;

import javax.inject.Inject;
import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.lang3.StringUtils;

@ServerEndpoint( value = "/bid/{bulletinId}" )
public class BidEndPoint {
	
	@Inject
	private SessionRegistry sessionRegistry;
	
	@OnOpen
	public void onOpen(Session session, @PathParam("bulletinId") String bulletinId, EndpointConfig endpointConfig) {
		session.setMaxIdleTimeout(60 * 60 * 1000);
		sessionRegistry.add(session);
	}	
	
	@OnClose
	public void onClose(Session session, @PathParam("bulletinId") String bulletinId, CloseReason closeReason) {
		sessionRegistry.remove(session);
	}
	
	@OnMessage
	public void onMessage(String message, Session session) throws IOException {
		if (StringUtils.isBlank(message))
			return;
		for (Session session2 : sessionRegistry.getAll(session.getPathParameters().get("bulletinId"))) {		
			if (session2.isOpen()) {
				session2.getBasicRemote().sendText(message);
			}
		}
	}
	
}
